package com.crrcdt.websocket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author lj on 2020/11/17.
 * @version 1.0
 */
public class UdpReceive implements Runnable {
    DatagramSocket datagramSocket =null;
    private int port;
    private String who;

    public UdpReceive(int port, String who) {
        this.port = port;
        this.who = who;
    }

    @Override
    public void run() {
        try {
            //指定自己的端口号
            datagramSocket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
        while (true){
            try {
                //准备接受包裹
                final byte[] bytes = new byte[1024];
                final DatagramPacket packet = new DatagramPacket(bytes, 0, bytes.length);
                datagramSocket.receive(packet);//阻塞式接受消息
                final byte[] data = packet.getData();//这里的data是字节byte
                //在控制台打印接受消息
                final String msg = new String(data, 0, data.length);
                System.out.println( who+": "+msg );
                if(msg.equals("bye")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        datagramSocket.close();
    }
}
